package com.rdc.qingkou.model;


import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.entity.Result;
import com.rdc.qingkou.model.imodel.ILoginCallBack;
import com.rdc.qingkou.retrofitService.ILoginRegisteService;
import com.rdc.qingkou.utils.MyUtils;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Headers;
import retrofit2.Response;


public class LoginModel  {

    private ILoginRegisteService iResult = MyUtils.getRetrofitProvider("").create(ILoginRegisteService.class);

    public void LoginRequest(String account, String password, final ILoginCallBack callBack) {
        //将cookie置空
        MyApplication.setCookie("");
        iResult.login(account, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<Result>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Response<Result> responseValue) {
                        Headers headers = responseValue.headers();
                        List<String> list = headers.values(("Set-Cookie"));
                        if (list.size() == 0) {
                            callBack.onFail("cookie为空！");
                            return;
                        } else {
                            MyApplication.setCookie(list.get(0));
                        }
                        Result value = responseValue.body();
                          if (value.getResult().equals("success")){
                              MyApplication.setUser(value.getUser());
                              callBack.onSuccess();
                          }else {
                              callBack.onFail(value.getReason());
                          }
                    }

                    @Override
                    public void onError(Throwable e) {
                              callBack.onFail("咦！网络好像出了点问题！");
                    }

                    @Override
                    public void onComplete() {

                    }
                });






    }
}
